package com.infore.dataReceiving.core.filter.instructions.air212;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.infore.dataReceiving.core.chain.Air212InstructionsChain;
import com.infore.dataReceiving.core.enums.Air212InstructionsTypeEnum;
import com.infore.dataReceiving.core.filter.Air212InstructionsFilter;
import com.infore.dataReceiving.dto.AirInstructionsDto;
import com.infore.dataReceiving.entity.air212.OrigData;
import com.infore.dataReceiving.entity.air212.OriginalData;
import com.infore.dataReceiving.entity.air212.RTEquipment;
import com.infore.dataReceiving.entity.air212.RTProject;
import com.infore.dataReceiving.repository.IBackControlLogRepository;
import com.infore.dataReceiving.util.CRCCheck;
import com.infore.dataReceiving.util.Air212InstructionsHandleUtil;
import com.infore.dataReceiving.util.RedisUtil;
import io.netty.channel.ChannelHandlerContext;

/**
 * 实时数据
 * @author 69457
 *
 */
public class RtdFilter implements Air212InstructionsFilter{
	
	public static Map<String, String> factorMap = new HashMap<String, String>();
	static {
		factorMap.put("a21026", "SO2");
		factorMap.put("a21004", "NO2");
		factorMap.put("a21005", "CO");
		factorMap.put("a05024", "O3");
		factorMap.put("a34004", "PM25");
		factorMap.put("a34002", "PM10");
		factorMap.put("a01007", "GUSTSPEED");
		factorMap.put("a01008", "GUSTDIR");
		factorMap.put("a01001", "TEMPERATURE");
		factorMap.put("a01002", "HUMIDITY");
		factorMap.put("a01006", "PRESSURE");
		factorMap.put("a21002", "NOX");
		factorMap.put("a21003", "NO");
	}
	
//	static {
//		factorMap.put("S01", "O2");
//		factorMap.put("S02", "烟气流速");
//		factorMap.put("S03", "烟气温度");
//		factorMap.put("S05", "烟气湿度");
//		factorMap.put("S08", "烟气压力");
//		factorMap.put("01", "烟尘");
//		factorMap.put("02", "SO2");
//		factorMap.put("03", "NOx");
//		factorMap.put("B02", "废气");
//		factorMap.put("01-Zs", "烟尘折算");
//		factorMap.put("02-Zs", "SO2折算");
//		factorMap.put("03-Zs", "NOX折算");
//	}
	
	@Override
	public void doFilter(ChannelHandlerContext ctx,AirInstructionsDto dto,
			Air212InstructionsChain chain,RedisUtil redisUtil,IBackControlLogRepository repository, boolean interrupt) {
		if(Air212InstructionsTypeEnum.air212_2011.getCn().equals(dto.getCn())) {
			interrupt = true;
			String dataTime = dto.getDataTime();
			String mn = dto.getMn();
			Timestamp timestamp = Air212InstructionsHandleUtil.getTimestamp(dataTime);
			
			
			//检查该数据对应的站点是否有补遗指令
//			Map<String, Object> timeMap = Air212InstructionsHandleUtil.dateMap.get(mn+"backControl");
//			boolean flag = true;
//			if(timeMap!=null) {
//				Timestamp begin = (Timestamp)timeMap.get("begin");
//				Timestamp end = (Timestamp)timeMap.get("end");
//				String mns = (String)timeMap.get("mn");
//				//检查数据是否在补遗指令规定的时间段内，站点mn号是否一致
//				if(timestamp.getTime()>=begin.getTime()&&timestamp.getTime()<=end.getTime()&&mn.equals(mns)) {
//					String[] factorDatas = dto.getFactorData().split(";");
//					setData(factorDatas,mn,timestamp,redisUtil,"0");
//					flag = false;
//				}
//			}
//			if(flag) {
//				//有datetime，是上传实时数据，无是提取实时数据,上传实时数据时间不能小于系统当前小时超过1小时
//				if(StringUtils.isEmpty(dataTime)||System.currentTimeMillis()-timestamp.getTime()>60*60*1000) {
//					System.out.println("没有DateTime或者DateTime小于系统当前时间超过1小时");
//				}else {
//					String[] factorDatas = dto.getFactorData().split(";");
//					setData(factorDatas,mn,timestamp,redisUtil,"1");
//				}
//			}
			
			String[] factorDatas = dto.getFactorData().split(";");
			if(!StringUtils.isEmpty(dataTime)) {
				if(System.currentTimeMillis()-timestamp.getTime()>60*60*1000) {
					setData(factorDatas,mn,timestamp,redisUtil,"0");
				}else {
					setData(factorDatas,mn,timestamp,redisUtil,"1");
				}
			}else {
				System.out.println("没有DateTime!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			}
			
			System.out.println("正在回复实时分钟消息！！！！！！！！！！！！！");
			String qn = dto.getQn();
			String pw = dto.getPw();
			String datas = "QN="+qn+";ST=91;CN=9014;PW="+pw+";MN="+mn+";Flag=4;CP=&&&&";
			int dataLength = datas.length();//数据段长度
			String crc = CRCCheck.crc16(datas, dataLength);
			String dataLengthString = Air212InstructionsHandleUtil.getDataLengthString(dataLength+"");
			String returnInfo = "##"+dataLengthString+datas+crc+"\r\n";
			ctx.channel().writeAndFlush(returnInfo);
		}
		chain.doFilter(ctx,dto,chain,redisUtil,repository,interrupt);
	}
	
	private void setData(String[] factorDatas,String mn,Timestamp timestamp,RedisUtil redisUtil,String flag) {
		for(String datas:factorDatas) {
			datas = ","+datas+",";
			Map<String, String> map = Air212InstructionsHandleUtil.getInstructions_Flag(datas);
			OriginalData originalData = new OriginalData();
			originalData.setMn(mn);
			String projectCode = factorMap.get(map.get("factorCode"));
			originalData.setProjectCode(projectCode==null?map.get("factorCode"):projectCode);
			originalData.setReceiveTime(timestamp);
			String valueString = Air212InstructionsHandleUtil.getInstructions_Rtd(datas);
			if(valueString==null||"".equals(valueString)) {
				originalData.setDataValue(valueString);
			}else {
				Double dataValue = Double.valueOf(valueString);
//				dataValue = auditMinuteDatas(projectCode, dataValue);
				originalData.setDataValue(dataValue.toString());
			}
			originalData.setDataState(map.get("flag"));
			if("0".equals(flag)) {
				redisUtil.lSet(mn+"backData", originalData);
			}else {
				redisUtil.lSet("originalData", originalData);
			}
		}
	}
	
//	private void setData(String[] factorDatas,String mn,Timestamp timestamp,RedisUtil redisUtil,String flag) {
//		RTEquipment equipment = new RTEquipment();
//		List<RTProject> projects = new ArrayList<RTProject>();
//		Long id1 = null;
//		for(String datas:factorDatas) {
//			datas = ","+datas+",";
//			Map<String, String> map = Air212InstructionsHandleUtil.getInstructions_Flag(datas);
//			OrigData originalData = new OrigData();
//			if("93532160754146".equals(mn)) {
//				originalData.setMoniEquiId(1L);
//				id1 = 1L;
//			}else if("93532160754147".equals(mn)){
//				originalData.setMoniEquiId(2L);
//				id1 = 2L;
//			}else if("93532160754148".equals(mn)){
//				originalData.setMoniEquiId(3L);
//				id1 = 3L;
//			}else {
//				originalData.setMoniEquiId(null);
//			}
//			String projectCode = "";
//			String dataValue = "";
//			if(map==null) {
//				Map<String, String> maps = Air212InstructionsHandleUtil.getInstructions_ProjectCode(datas);
//				projectCode = maps.get("factorCode");
//				dataValue = maps.get("value");
//			}else {
//				projectCode = map.get("factorCode");
//				dataValue = Air212InstructionsHandleUtil.getInstructions_Rtd(datas);
//				originalData.setDataState(map.get("flag"));
//			}
//			String projectCodes = factorMap.get(projectCode);
//			originalData.setMoniProjName(projectCodes==null?projectCode:projectCodes);
//			originalData.setTime(timestamp);
//			originalData.setDataValue(dataValue);
//			if("0".equals(flag)) {
//				redisUtil.lSet("backData", originalData);
//			}else {
//				redisUtil.lSet("originalData", originalData);
//				RTProject rtproject  = new RTProject();
//				rtproject.setMoniProjCode(projectCode);
//				rtproject.setName(projectCodes);
//				rtproject.setValue(dataValue);
//				projects.add(rtproject);
//			}
//		}
//		equipment.setId(id1);
//		equipment.setProjects(projects);
//		equipment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp));
//		redisUtil.lSet("realDatas", equipment);
//	}
	
	
	/**
	 * 分钟数据审核修约
	 * @param projectCode 因子code
	 * @param avgValue 浓度
	 * @param result 修订浓度值
	 */
	private Double auditMinuteDatas(String projectCode, Double avgValue) {
		Double result = null;
		if("SO2".equals(projectCode)) {
			if(avgValue!=null) {
				if(avgValue<(-9)) {
					result = null;
				}else if(avgValue<3) {
					result = 3d;
				}else {
					result = avgValue;
				}
			}
		}else if("NO2".equals(projectCode)) {
			if(avgValue!=null) {
				if(avgValue<(-7)) {
					result = null;
				}else if(avgValue<2) {
					result = 2d;
				}else {
					result = avgValue;
				}
			}
		}else if("O3".equals(projectCode)) {
			if(avgValue!=null) {
				if(avgValue<(-8)) {
					result = null;
				}else if(avgValue<2) {
					result = 2d;
				}else {
					result = avgValue;
				}
			}
		}else if("CO".equals(projectCode)) {
			if(avgValue!=null) {
				if(avgValue<(0)) {
					result = null;
				}else if(avgValue<0.05) {
					result = 0.05;
				}else {
					result = avgValue;
				}
			}
		}else if("PM25".equals(projectCode)) {
			if(avgValue!=null) {
				if(avgValue<(-5)) {
					result = null;
				}else if(avgValue<=5) {
					result = 2d;
				}else {
					result = avgValue;
				}
			}
		}else if("PM10".equals(projectCode)) {
			if(avgValue!=null) {
				if(avgValue<(0)) {
					result = null;
				}else if(avgValue<=5) {
					result = 3d;
				}else {
					result = avgValue;
				}
			}
		}else {
			result = avgValue;
		}
		return result;
	}

}
